<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 配送方式类
 * @author   allen.qiang
 * @version 1.0
 */

class sysSend {

    /**
     * 查询配送方式
     * @param array $arg_array
     * @return null
     */
    public function searchSendType( &$arg_array ) {
        
        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //配送方式ID
        if (isset($arg_array['sendTypeID']) && is_numeric($arg_array['sendTypeID'])) {
            $sql .= ' AND sendTypeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['sendTypeID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if (isset($arg_array['is_take_their']) && in_array($arg_array['is_take_their'], array(0, 1))) {
            $sql .= ' AND is_take_their = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['is_take_their'];
        }


        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM sys_sendtype ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_sendtype ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            $item_array = array();

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'sendTypeID' => $item->sendTypeID,
                    'sendTypeName' => $item->sendTypeName,
                    'description' => $item->description,
                    'useFlg' => $item->useFlg,
                    'is_take_their' => $item->is_take_their,
                    'useFlgName' => $item->useFlg ? '启用' : '禁用',
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询配送区域
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sendTypeID' => int 配送方式ID
     *      'send_region_id' => int 配送区域ID
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchSendArea( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //配送方式ID
        if (isset($arg_array['sendTypeID']) && is_numeric($arg_array['sendTypeID'])) {
            $sql .= ' AND sendTypeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['sendTypeID'];
        }

        //地图区域ID
        if (isset($arg_array['areaID']) && is_numeric($arg_array['areaID'])) {
            $sql .= ' AND areaID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['areaID'];
        }

        //使用标志
        if (isset($arg_array['send_region_id']) && is_numeric($arg_array['send_region_id'])) {
            $sql .= ' AND send_region_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['send_region_id'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM sys_send_area ' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM sys_send_area ' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'sendTypeID' => $item->sendTypeID,
                    'send_region_id' => $item->send_region_id,
                    'send_region_name' => $item->send_region_name,
                    'freight' => $item->freight,
                    'ykg' => $item->ykg,
                    'overweight_freight' => $item->overweight_freight,
                    'areaID'=>$item->areaID,
                    'areaName' => $item->areaName,
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 新增/修改配送区域
     * @param array $arg_array 参数数组
     * $arg_array = array (
     *       'sendTypeID' => int 配送方式ID
     *       'send_region_id' => int 配送区域ID
     *       'send_region_name' => string 配送区域名称
     *       'ykg' => int 首重
     *       'freight' => double 首重运费
     *       'overweight_freight' => double 超重运费
     *       'province_box' => array 身份数组  【可选】
     *       'city_box' => array 市区数组      【可选】
     *       'county_box' => array 地区数组    【可选】
     * )
     * @return array
     * @throws Exception
     */
    public function editSendArea ( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['sendTypeID'], $arg_array['send_region_id'], $arg_array['send_region_name'], $arg_array['ykg'], $arg_array['freight'], $arg_array['overweight_freight'],$arg_array['areaID'],$arg_array['areaName']))
            return array( 'code' => 400, 'message' => '参数错误' );

        if (!quanli_is_int($arg_array['sendTypeID'], 2) || !quanli_is_int($arg_array['send_region_id'], 2) || !quanli_is_int($arg_array['areaID'], 2) )
            return array( 'code' => 400, 'message' => '参数错误' );

        if (empty($arg_array['send_region_name']))
            return array( 'code' => 400, 'message' => '配送区域名称不能为空' );

        if (empty($arg_array['areaName']))
            return array( 'code' => 400, 'message' => '地图区域名称不能为空' );

        if (!quanli_is_int($arg_array['ykg'], 1))
            return array( 'code' => 400, 'message' => '首重必须是大于0的整数' );

        if (!is_money($arg_array['freight'], 2))
            return array( 'code' => 400, 'message' => '首重运费必须是大于等于0的金额' );

        if (!is_money($arg_array['overweight_freight'], 2))
            return array( 'code' => 400, 'message' => '超重运费必须是大于等于0的金额' );


        try {


            //查询配送方式
            $send_obj = new entity('sys_sendtype');
            $send_obj->sendTypeID = $arg_array['sendTypeID'];
            if (!$G_SHOP->DBCA->fetch($send_obj))
                throw new Exception('配送方式信息没有找到', 404);

            //配送区域主表信息
            $send_area_obj = new entity('sys_send_area');
            $send_area_obj->sendTypeID = $arg_array['sendTypeID'];
            if ($arg_array['send_region_id'] > 0) {

                //查询配送区域
                $send_area_obj->send_region_id = $arg_array['send_region_id'];
                if (!$G_SHOP->DBCA->fetch($send_area_obj))
                    throw new Exception('配送区域信息没有找到', 404);
                $send_area_obj->creator = $arg_array['creator'];

            } else {
                $send_area_obj->creator = $arg_array['creator'];
            }
            $send_area_obj->send_region_name = convertVar($arg_array['send_region_name']);
            $send_area_obj->freight = $arg_array['freight'];
            $send_area_obj->ykg = $arg_array['ykg'];
            $send_area_obj->overweight_freight = $arg_array['overweight_freight'];
            $send_area_obj->areaID = $arg_array['areaID'];
            $send_area_obj->areaName = $arg_array['areaName'];

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，请与系统管理员联系' );
            }

        }


        try {

            //开始事务
            $G_SHOP->DBCA->beginTransaction();

            //保存/更新配送区域主表信息
            if (!$G_SHOP->DBCA->save($send_area_obj))
                throw new Exception('系统错误，请与系统管理员联系', 500);

            $send_region_id = $arg_array['send_region_id'];
            if ($send_region_id == 0)
                $send_region_id = $G_SHOP->DBCA->insert_id;

            //提交事务
            $G_SHOP->DBCA->commit();

        } catch (Exception $e) {

            //回滚事务
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() == 0)
                error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误，请与系统管理员联系' );

        }

        if ($arg_array['send_region_id'] == 0)
            return array( 'code' => 200, 'message' => '配送区域保存成功' );
        else
            return array( 'code' => 200, 'message' => '配送区域修改成功' );

    }


    /**
     * 新增或修改配送方式
     * @param array $arg_array 参数数组
     * @return array
     * @throws Exception
     */
    public function editSendType ( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['sendTypeID'], $arg_array['sendTypeName'], $arg_array['description'], $arg_array['pay_type'],
            $arg_array['operator']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!quanli_is_int($arg_array['sendTypeID'])) {
            $arg_array['sendTypeID'] = 0;
        }

        if (empty($arg_array['sendTypeName'])) {
            return array( 'code' => 400, 'message' => '配送方式名称不能为空' );
        }

        if (empty($arg_array['pay_type']) || !is_array($arg_array['pay_type'])) {
            return array( 'code' => 400, 'message' => '请选择支付方式类型' );
        }


        try {

            //开始事务
            $G_SHOP->DBCA->beginTransaction();

            //保存配送方式
            $send_type_obj = new entity('sys_sendtype');
            if ($arg_array['sendTypeID'] > 0) {

                //查询配送方式
                $send_type_obj->sendTypeID = $arg_array['sendTypeID'];
                if (!$G_SHOP->DBCA->fetch($send_type_obj))
                    throw new Exception('配送方式信息没有找到', 400);

                //删除配送方式对应的支付类型数据
                $sql = 'DELETE FROM sys_sendtype_pay WHERE sendTypeID = ?';
                $G_SHOP->DBCA->stmt_query($sql, 'i', $arg_array['sendTypeID']);

            } else {

                $send_type_obj->creator = $arg_array['operator'];
                $send_type_obj->useFlg = 1;

            }
            $send_type_obj->sendTypeName = $arg_array['sendTypeName'];
            $send_type_obj->description = $arg_array['description'];
            if (!$G_SHOP->DBCA->save($send_type_obj))
                throw new Exception('系统错误，请与系统管理员联系', 500);


            $sendTypeID = $arg_array['sendTypeID'];

            if ($sendTypeID == 0)
                $sendTypeID = $G_SHOP->DBCA->insert_id;


            foreach($arg_array['pay_type'] as &$pay_type) {

                if (!in_array($pay_type, array(1, 2)))
                    throw new Exception('支付类型错误', 400);

                //保存配送方式支付类型
                $pay_type_obj = new entity('sys_sendtype_pay');
                $pay_type_obj->creator = $arg_array['operator'];
                $pay_type_obj->sendTypeID = $sendTypeID;
                $pay_type_obj->pay_type = $pay_type;
                if (!$G_SHOP->DBCA->save($pay_type_obj))
                    throw new Exception('系统错误，请与系统管理员联系', 500);

            }

            //提交事务
            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '配送方式保存成功' );

        } catch (Exception $e) {

            //回滚事务
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，请与系统管理员联系' );
            }

        }

    }

    /**
     * 删除配送区域
     * @param array $arg_array 配送区域ID数组
     * $arg_array = array(
     *       0 => int, 区域ID
     *       1 => int, 区域ID
     *       ...
     * )
     * @param bool $isTransaction 是否使用事务
     * @return array
     * @throws Exception
     */
    public function deleteSendArea ( $arg_array, $isTransaction=true ) {

        global $G_SHOP;

        if (empty($arg_array) || !is_array($arg_array))
            return array( 'code' => 400, 'message' => '参数错误' );

        try {

            //开始事务
            if ($isTransaction)
                $G_SHOP->DBCA->beginTransaction();

            foreach($arg_array as &$id) {

                if (!is_numeric($id))
                    continue;

                //删除配送区域
                $send_area_obj = new entity('sys_send_area');
                $send_area_obj->send_region_id = $id;
                if (!$G_SHOP->DBCA->fetch($send_area_obj))
                    continue;
                if (!$G_SHOP->DBCA->delete($send_area_obj))
                    throw new Exception('系统错误，请与系统管理员联系', 500);

            }

            //提交事务
            if ($isTransaction)
                $G_SHOP->DBCA->commit();

        } catch (Exception $e) {

            //回滚事务
            if ($isTransaction)
                $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，请与系统管理员联系' );
            }

        }

        return array( 'code' => 200, 'message' => '配送区域删除成功' );

    }


    /**
     * 删除配送方式
     * @param array $arg_array 配送方式ID数组
     * $arg_array = array(
     *       0 => int, 配送方式ID
     *       1 => int, 配送方式ID
     *       ...
     * )
     * @return array
     * @throws Exception
     */
    public function deleteSendType ( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array[0])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            //开始事务
            $G_SHOP->DBCA->beginTransaction();

            foreach($arg_array as &$id) {

                if (!quanli_is_int($id))
                    continue;

                //删除配送方式
                $send_type_obj = new entity('sys_sendtype');
                $send_type_obj->sendTypeID = $id;
                if (!$G_SHOP->DBCA->fetch($send_type_obj))
                    continue;
                if (!$G_SHOP->DBCA->delete($send_type_obj))
                    throw new Exception('系统错误，请与系统管理员联系1', 500);

                //检查配送方式下是否已配置区域
                $area_arg_array = array(
                    'sendTypeID' => $id
                );
                $area_array = $this->searchSendArea( $area_arg_array );
                if ($area_array) {

                    //生成要删除配送区域ID数组
                    $del_arg_array = array();
                    foreach($area_array as &$area) {
                        $del_arg_array[] = $area['send_region_id'];
                    }

                    //删除配送区域
                    $result_array = $this->deleteSendArea($del_arg_array, false);
                    if ($result_array['code'] != 200)
                        throw new Exception($result_array['message'], $result_array['code']);

                }


            }

            //提交事务
            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '配送方式删除成功' );

        } catch (Exception $e) {

            //回滚事务
            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，请与系统管理员联系3' );
            }

        }

    }

    /**
     * 配送方式启用/禁用
     * @param $arg_array
     * $arg_array = array(
     *       sendTypeID => int 配送方式ID【必选】
     *       flg => int 配送方式状态【必选】
     * )
     * @return array
     */
    public function changeSendTypeUseflg ( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['sendTypeID'], $arg_array['flg']) || !quanli_is_int($arg_array['sendTypeID']) || !in_array($arg_array['flg'], array(0,1)))
            return array( 'code' => 400, 'message' => '参数错误' );

        try {

            //查询配送方式
            $sendType_obj = new entity('sys_sendtype');
            $sendType_obj->sendTypeID = $arg_array['sendTypeID'];
            if (!$G_SHOP->DBCA->fetch($sendType_obj))
                return array( 'code' => 404, 'message' => '配送方式信息没有找到' );

            if ($arg_array['flg']) {

                if ($sendType_obj->useFlg == 0) {
                    return array( 'code' => 406, 'message' => '配送方式已禁用' );
                }
                $sendType_obj->useFlg = 0;

            } else {

                if ($sendType_obj->useFlg == 1) {
                    return array( 'code' => 406, 'message' => '配送方式已启用' );
                }
                $sendType_obj->useFlg = 1;

            }
            $G_SHOP->DBCA->save($sendType_obj);

            if ($arg_array['flg'])
                return array( 'code' => 200, 'message' => '配送方式禁用成功' );
            else
                return array( 'code' => 200, 'message' => '配送方式启用成功' );

        } catch (Exception $e) {
            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

}